package com.inspector.app.ui.task

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.ObservableBoolean
import androidx.fragment.app.viewModels
import androidx.lifecycle.viewmodel.viewModelFactory
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.example.commen.utile.SingleClick
import com.google.android.material.tabs.TabLayoutMediator
import com.hjq.toast.Toaster
import com.inspector.app.R
import com.inspector.app.databinding.FragmentTaskBinding
import com.inspector.app.di.util.UI
import com.inspector.app.ui.base.BaseDJFragment
import com.inspector.app.ui.task.TaskExecutionDialog.TaskExecutionListener
import com.inspector.app.ui.vo.TaskClickType
import com.inspector.app.ui.vo.TaskItem
import com.inspector.app.ui.vo.TaskTabItem
import com.inspector.app.util.LogUtil
import java.util.Date

class TaskFragment : BaseDJFragment<FragmentTaskBinding>() {

    private val tabItems =
        arrayOf(TaskTabItem(tableTitle = "系统任务"), TaskTabItem(tableTitle = "我的任务"))
    val statusList = mutableListOf("全部状态", "未开始", "进行中", "已完成", "手动终止")


    private val viewModel by viewModels<TaskViewModel> {
        viewModelFactory {
            addInitializer(TaskViewModel::class) {
                TaskViewModel(TaskRepository(this@TaskFragment))
            }
        }
    }

    private val systemTaskVisible = ObservableBoolean()

    override fun provideViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentTaskBinding {
        return FragmentTaskBinding.inflate(inflater, container, false)
    }


    override fun setupView(view: View, savedInstanceState: Bundle?) {
        viewBinding.systemTask = systemTaskVisible
        viewBinding.lifecycleOwner = this
        viewBinding.executePendingBindings()

        viewBinding.itemTVDate.text = UI.formatDate(Date(), "yyyy/MM/dd")

        viewModel.systemTaskPosition.observe(viewLifecycleOwner) {
            systemTaskVisible.set(it.systemTaskPos)
            systemTaskVisible.notifyChange()
            showProgress("列表数据加载中...")
        }

        viewModel.getItems()
            .observe(viewLifecycleOwner) { taskData ->
                LogUtil.e("TaskFragment", "列表数据 items:${taskData.list}")
                dismissProgress()

                val items = taskData.list
                val params = viewModel.systemTaskPosition.value ?: return@observe
                val systemTask = params.systemTaskPos
                val position = if (systemTask) 0 else 1

                if (systemTask) {
                    tabItems[position].tabItems = items
                } else {
                    viewBinding.smartRefreshLayout.setEnableLoadMore(!taskData.isLastPage)
                    if (params.pageNumber == 1) {
                        tabItems[position].tabItems = items
                    } else {
                        val newItems = mutableListOf<TaskItem>()
                        val oldItems = tabItems[position].tabItems
                        if (!oldItems.isNullOrEmpty()) {
                            newItems.addAll(oldItems)
                        }
                        if (!items.isNullOrEmpty()) {
                            newItems.addAll(items)
                        }
                        tabItems[position].tabItems = newItems
                    }
                }


                viewBinding.viewPager2.adapter?.notifyItemChanged(position)
                viewBinding.noDataLayout.emptyLayout.visibility =
                    if (tabItems[position].tabItems.isNullOrEmpty()) View.VISIBLE else View.GONE

                viewBinding.smartRefreshLayout.finishRefresh()
                viewBinding.smartRefreshLayout.finishLoadMore() //结束加载

            }

        setupViewPager()

        viewBinding.smartRefreshLayout.setOnRefreshListener {
            val systemTask = viewModel.systemTaskPosition.value ?: return@setOnRefreshListener
            if (systemTask.systemTaskPos) {
                viewModel.systemTaskPosition.value = systemTask?.copy()
            } else {
                systemTask?.copy()?.apply {
                    pageNumber = 20
                    pageSize = 1
                    // TODO: []
                }
                viewModel.systemTaskPosition.value = systemTask
            }
        }
        viewBinding.smartRefreshLayout.setOnLoadMoreListener {
            val systemTask = viewModel.systemTaskPosition.value ?: return@setOnLoadMoreListener
            systemTask.pageNumber += 1
            viewModel.systemTaskPosition.value = systemTask.copy()
        }



        SingleClick(viewBinding.search) {


            Toaster.show("点击了搜索")

        }

        SingleClick(viewBinding.timeLayout) {
            var timePickerView = TimePickerBuilder(context) { date, v ->
                val systemTask = viewModel.systemTaskPosition.value ?: return@TimePickerBuilder
                systemTask.startTime = UI.formatDate(date, "yyyy-MM-dd HH:mm:ss")
                systemTask.endTime = UI.formatDate(UI.addOneDayToDate(date), "yyyy-MM-dd HH:mm:ss")
                viewBinding.itemTVDate.text = UI.formatDate(date, "yyyy/MM/dd")
                viewModel.systemTaskPosition.value = systemTask?.copy()
            }.setType(booleanArrayOf(true, true, true, true, true, true))
                .setCancelText("取消")
                .setCancelColor(resources.getColor(R.color.color_EFF0F1, context?.theme))
                .setSubmitText("确认")
                .setSubmitColor(resources.getColor(R.color.color_EFF0F1, context?.theme))
                .setSubCalSize(15)
                .setTitleText("选择时间")
                .setTitleColor(resources.getColor(R.color.color_EFF0F1, context?.theme))
                .setTitleSize(18)
                .setTextColorCenter(Color.WHITE)
                .setTextColorOut(resources.getColor(R.color.colorGreyDivier, context?.theme))
                .setLineSpacingMultiplier(1.6f)
                .setTitleBgColor(resources.getColor(R.color.color_1C1C1C, context?.theme))
                .setBgColor(resources.getColor(R.color.bg2C2C2C, context?.theme))
                .setContentTextSize(18)
                .setDividerColor(resources.getColor(R.color.color_EFF0F1, context?.theme))
                .isCyclic(true)
                .isCenterLabel(true)
                .build()
            timePickerView.show()


        }

        SingleClick(viewBinding.statusLayout) {
            var optionsPickerBuilder =
                OptionsPickerBuilder(context) { option1, option2, option3, v ->
                    val systemTask =
                        viewModel.systemTaskPosition.value ?: return@OptionsPickerBuilder
                    systemTask.status = selectState(statusList[option1])
                    viewModel.systemTaskPosition.value = systemTask
                    viewBinding.itemTVStatus.text = statusList[option1]
                }.setCancelText("取消")
                    .setCancelColor(resources.getColor(R.color.color_EFF0F1, context?.theme))
                    .setSubmitText("确认")
                    .setSubmitColor(resources.getColor(R.color.color_EFF0F1, context?.theme))
                    .setSubCalSize(15)
                    .setTitleText("选择状态")
                    .setTitleColor(resources.getColor(R.color.color_EFF0F1, context?.theme))
                    .setTitleSize(18)
                    .setTitleBgColor(resources.getColor(R.color.color_1C1C1C, context?.theme))
                    .setBgColor(resources.getColor(R.color.bg2C2C2C, context?.theme))
                    .setContentTextSize(18)
                    .setItemVisibleCount(11)
                    .setDividerColor(resources.getColor(R.color.color_EFF0F1, context?.theme))
                    .isCenterLabel(true)
                    .setLineSpacingMultiplier(1.6f)
                    .setTextColorCenter(Color.WHITE)
                    .setTextColorOut(resources.getColor(R.color.colorGreyDivier, context?.theme))
                    .setSelectOptions(0)
                    .build<String>()
            optionsPickerBuilder.setPicker(statusList)
            optionsPickerBuilder.show()

        }
    }


    fun selectState(month: String): String = when (month) {
        "所有状态" -> ""
        "未开始" -> "1"
        "进行中" -> "2"
        "已完成" -> "3"
        "手动终止" -> "4"
        else -> ""
    }

    private fun setupViewPager() {
        viewBinding.viewPager2.apply {
            orientation = ViewPager2.ORIENTATION_HORIZONTAL
            (getChildAt(0) as RecyclerView).overScrollMode = RecyclerView.OVER_SCROLL_NEVER
        }

        viewBinding.viewPager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                val tabList = tabItems[position].tabItems
                if (tabList.isNullOrEmpty()) {
                    val params = viewModel.systemTaskPosition.value ?: return
                    params.pageNumber = 1
                    params.systemTaskPos = position == 0
                    viewModel.systemTaskPosition.value = params.copy()
                } else {
                    viewModel.systemTaskPosition.value?.systemTaskPos = position == 0

                }
                viewBinding.noDataLayout.emptyLayout.visibility =
                    if (tabItems[position].tabItems.isNullOrEmpty()) View.VISIBLE else View.GONE
            }
        })

        val adapter = TaskTabAdapter(tabItems) { clickType, item ->
            onItemClick(clickType, item)
        }
        viewBinding.viewPager2.adapter = adapter

        TabLayoutMediator(
            viewBinding.tabLayout,
            viewBinding.viewPager2
        ) { tab, position ->
            tab.text = tabItems[position].tableTitle
        }.attach()
    }

    private fun onItemClick(clickType: TaskClickType, item: TaskItem) {
        TaskFragmentClickUtils.setClickType(
            clickType,
            item,
            context,
            childFragmentManager,
            object : TaskExecutionListener {
                override fun onTaskExecutionSucceed(clickType: TaskClickType) {
                    when (clickType) {
                        TaskClickType.APPLY_TYPE, TaskClickType.PASSWORD_TYPE -> {
                            val systemTask = viewModel.systemTaskPosition.value ?: return
                            viewModel.systemTaskPosition.value = systemTask?.copy()
                        }

                        else -> {

                        }
                    }
                }

                override fun error() {

                }
            }
        )
    }

    override fun initListener() {}

    override fun initData() {}
}
